import { get, post } from '../utils/request'

// 获取余额接口
const getBalance = async () => {
  try {
    // 调用后端接口 /h5/my/getBalance (后端是GET请求)
    const result = await get('/h5/my/getBalance')

    if (result.success) {
      // 适配BigDecimal类型，将数字转换为字符串格式
      const balanceData = result.data
      if (balanceData && balanceData.balance !== undefined) {
        // 如果是数字类型，转换为字符串并保留2位小数
        if (typeof balanceData.balance === 'number') {
          balanceData.balance = balanceData.balance.toFixed(2)
        } else if (balanceData.balance && typeof balanceData.balance === 'object') {
          // 如果是BigDecimal对象，取toString()值
          balanceData.balance = balanceData.balance.toString()
        }
      }
      
      return {
        success: true,
        data: balanceData
      }
    } else {
      return {
        success: false,
        message: result.message || '获取余额失败'
      }
    }
  } catch (error) {
    console.error('获取余额失败:', error)
    return {
      success: false,
      message: '网络错误，请检查网络连接'
    }
  }
}

// 获取入账记录接口
const getIncomeRecords = async (params = {}) => {
  try {
    // 调用后端接口 /h5/my/getIncomeRecords
    const result = await post('/h5/my/getIncomeRecords', params)

    if (result.success) {
      return {
        success: true,
        data: result.data
      }
    } else {
      return {
        success: false,
        message: result.message || '获取入账记录失败'
      }
    }
  } catch (error) {
    console.error('获取入账记录失败:', error)
    return {
      success: false,
      message: '网络错误，请检查网络连接'
    }
  }
}

// 修改银行卡信息接口
const modifyBankInfo = async (bankInfo) => {
  try {
    // 调用后端接口 /h5/my/modifyBankInfo
    const result = await post('/h5/my/modifyBankInfo', bankInfo)

    if (result.success) {
      return {
        success: true,
        message: result.message || '银行卡信息保存成功'
      }
    } else {
      return {
        success: false,
        message: result.message || '银行卡信息保存失败'
      }
    }
  } catch (error) {
    console.error('修改银行卡信息失败:', error)
    return {
      success: false,
      message: '网络错误，请检查网络连接'
    }
  }
}

// 提现接口
const withdraw = async (amount) => {
  try {
    // 调用后端接口 /h5/my/withdraw
    const result = await post('/h5/my/withdraw', { amount: amount })

    if (result.success) {
      return {
        success: true,
        message: result.message || '提现申请提交成功'
      }
    } else {
      return {
        success: false,
        message: result.message || '提现申请提交失败'
      }
    }
  } catch (error) {
    console.error('提现申请失败:', error)
    return {
      success: false,
      message: '网络错误，请检查网络连接'
    }
  }
}

// 获取提现记录接口
const getWithdrawRecords = async (params = {}) => {
  try {
    // 调用后端接口 /h5/my/getWithdrawRecords
    const result = await post('/h5/my/getWithdrawRecords', params)

    if (result.success) {
      // 处理后端返回的数据格式
      const data = result.data
      
      // 格式化数据，适配前端显示
      const formattedData = {
        cumulative: data.cumulative || 0,
        total: data.total || 0,
        list: data.list ? data.list.map(record => ({
          id: record.id,
          status: mapTradeStatusToFrontend(record.tradeStatus),
          statusText: getStatusText(record.tradeStatus),
          amount: record.amount ? parseFloat(record.amount) : 0,
          applyTime: record.applyTime,
          bankName: record.bankName || '',
          cardNo: formatCardNo(record.bankAccount),
          withdrawNo: record.withdrawNo || '',
          processor: record.dealer || '系统自动处理',
          withdrawMessage: record.withdrawMessage || '',
          failReason: record.withdrawMessage?.includes('失败') ? record.withdrawMessage : ''
        })) : []
      }
      
      return {
        success: true,
        data: formattedData
      }
    } else {
      return {
        success: false,
        message: result.message || '获取提现记录失败'
      }
    }
  } catch (error) {
    console.error('获取提现记录失败:', error)
    return {
      success: false,
      message: '网络错误，请检查网络连接'
    }
  }
}

// 状态映射函数
const mapTradeStatusToFrontend = (tradeStatus) => {
  // 后端状态：0-待审核 1-审核失败 2-审核通过 3-打款成功
  // 前端状态：processing-处理中 success-成功 failed-失败
  switch (tradeStatus) {
    case '0':
      return 'processing'
    case '1':
      return 'failed'
    case '2':
      return 'processing'
    case '3':
      return 'success'
    default:
      return 'failed'
  }
}

// 获取状态文本
const getStatusText = (tradeStatus) => {
  switch (tradeStatus) {
    case '0':
      return '待审核'
    case '1':
      return '审核失败'
    case '2':
      return '审核通过'
    case '3':
      return '打款成功'
    default:
      return '未知状态'
  }
}

// 格式化银行卡号
const formatCardNo = (cardNo) => {
  if (!cardNo) return ''
  if (cardNo.length <= 4) return cardNo
  return '尾号' + cardNo.substring(cardNo.length - 4)
}

export {
  getBalance,
  getIncomeRecords,
  modifyBankInfo,
  withdraw,
  getWithdrawRecords
}